package com.chy.ruoyi.vue.codegen.controller;

import com.chy.ruoyi.vue.codegen.core.text.Convert;
import com.chy.ruoyi.vue.codegen.domain.GenTable;
import com.chy.ruoyi.vue.codegen.domain.GenTableColumn;
import com.chy.ruoyi.vue.codegen.service.IGenTableColumnService;
import com.chy.ruoyi.vue.codegen.service.IGenTableService;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;

@RequestMapping("/gen")
@RestController
public class CodeGenController {

    @Autowired
    private IGenTableService genTableService;

    @Autowired
    private IGenTableColumnService genTableColumnService;

    /**
     * 查询数据表字段列表
     */
    @GetMapping(value = "/column/{talbleId}")
    public String columnList(@PathVariable Long talbleId)
    {
        System.out.println(talbleId);
        List<GenTableColumn> list = genTableColumnService.selectGenTableColumnListByTableId(talbleId);
        return  "hello"+list.size();
    }

    @GetMapping(value = "/generate")
    public void generate() {
        //第一步：检查是否存在历史数据并删除
        String tableName = "admin";
        GenTable req=new GenTable();
        req.setTableName(tableName);
        List<GenTable> genTables = genTableService.selectGenTableList(req);
        if (!CollectionUtils.isEmpty(genTables)) {
           // log.warn("表{}生成数据已存在，即将删除历史数据", tableName);
            Long[] array = new Long[genTables.size()];
            genTables.stream().map(GenTable::getTableId).collect(Collectors.toList()).toArray(array);
            genTableService.deleteGenTableByIds(array);
        }
        //第二步：导入表结构
        String[] tableNames = Convert.toStrArray(tableName);
        // 查询表信息
        List<GenTable> tableList = genTableService.selectDbTableListByNames(tableNames);
        genTableService.importGenTable(tableList);

        //第三步：生成压缩文件
        byte[] data = genTableService.downloadCode(tableNames);
        genCode("ruoyi.zip", data);
    }
    /**
     * 生成zip文件
     *
     * @param fileName 目标压缩文件名
     * @param data     字节数组
     */
    public void genCode(String fileName, byte[] data) {
        try {
            IOUtils.write(data, new FileOutputStream(new File(fileName)));
        } catch (IOException e) {
           // log.error("", e);
            System.out.println("ex"+e);
        }
    }
}
